<template>
	<div>
		<!-- 注意：必须关闭自动上传属性 auto-upload -->
        <el-upload 
			ref="fileUpload"
            :http-request="Upload" 
            :headers="headers" 
            :file-list="productImageList"
            :multiple="false" 
            :list-type="listType" 
			:show-file-list="showFileList"
            :limit="12"
			:on-remove="removeImage" 
            :before-upload="beforeAvatarUpload"
			:auto-upload="false" 
            :on-change="selectChange" 
			:on-preview="handlePictureCardPreview"
			:accept="accept"
            action="" 
            class="cropper-upload-box">
			<!-- <i slot="default" class="el-icon-plus"></i> -->
			<slot></slot>
		</el-upload>
        <cropper v-if="showCropper" :dialog-visible="showCropper" :cropper-img="cropperImg" :zoomScale="zoomScale" @update-cropper="updateCropper" @colse-dialog="closeDialog" :width="width" @upload-img="uploadImg" />
		<el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
	</div>
</template>

<script>
	export default {
		name: "cropperUpload",
		data() {
			return {
				productImageList: [],

				showCropper: false, // 是否显示裁剪框
				cropperImg: "", // 需要裁剪的图片
				uploadFile: "",
				accept: "",
				dialogImageUrl: '',
            	dialogVisible: false
			};
		},
		props: {
			defaultImgList: { // 默认显示的图片列表
				type: Array,
				default: () => []
			},
			zoomScale: { // 裁剪比例，默认1:1
				type: Array,
				default: () => [1, 1]
			},
			listType: { //文件列表的类型
				type: String,
				default: "text"
			},
			multiple: { //是否支持多选文件，也用于表示可上传多张或单张图片
				type: Boolean,
				default: false
			},
			showFileList: { //是否显示已上传文件列表
				type: Boolean,
				default: false
			},
			isCropper:{ //开启裁剪
				type: Boolean,
				default: false
			},
			width: {
				type: Number,
				default: 700
			}
		},
		watch: {
			defaultImgList: {
				handler: function(newVal, oldVal) {
					this.productImageList = newVal // 赋值
				},
				deep: true
			}
		},
        computed: {
			headers() {
				return this.$store.state.header
			}
		},
		created(){
			if(this.isCropper){
				this.accept = '.jpg,.png'
			}
		},
		methods: {
			beforeAvatarUpload(file) {
				const isLt2M = file.size / 1024 / 1024 < 20; // 原图片
				// const isLt2M = this.uploadFile.size / 1024 / 1024 < 1;  //裁剪后的图片（会比原图片大很多，应该是转成Blob的原因导致）
				if (!isLt2M) {
					this.$message.error("上传图片大小不能超过 20MB!");
					this.noCanUpload = true // 如果这里被拦截，将自动删除不能上传的图片
					return false
				}
				// return isLt2M
			},
			removeImage(file, fileList) {
				const index = this.productImageList.findIndex(item => {
					return item.uid == file.uid;
				});
				if (index > -1) {
					this.productImageList.splice(index, 1);
				}
				if(this.listType != 'picture-card'){
					this.$emit('getUpload', this.productImageList, file) // 把最新上传的图片列表返回
				}
			},
			Upload(file) {
				// console.log(file)
				let blob = this.uploadFile;
				const files = new window.File(
					[blob],
					file.file.name,
					{ type: file.file.type }
				);

				let data = new FormData();
				data.append('file', files);

				let configs = {
					headers: {
						"Content-Type": "multipart/form-data;boundary=" + new Date().getTime()
					}
				};
				const loading = this.$loading({
					lock: true
				});
				// data为file格式
				this.$axios.post('/upload/', data, configs).then((res) => {
					if(this.listType != 'picture-card'){
						this.productImageList.push({
							path: res.path,
							url: res.url,
							uid: file.file.uid,
							name: file.file.name,
							savename: res.path,
							size: file.file.size
						});
					}
					
					loading.close();
					this.showCropper = false;
					file.file.status = "success"
					this.$emit('getUpload', res, file.file) // 把最新上传的图片列表返回
				}).catch(function(error) {
					console.log(error)
					loading.close();
				})
			},

			// 更新图片
			updateCropper() {
				if (!this.noCanUpload) {
					let fileList = this.$refs.fileUpload.uploadFiles // 获取文件列表
					let index02 = fileList.findIndex(item => { // 把取消裁剪的图片删除
						return item.uid == this.currentFile.uid;
					});
					fileList.splice(index02, 1)
				}

				let index = this.$refs.fileUpload.$children.length - 1;
				this.$refs.fileUpload.$children[index].$el.click();
			},
			// 关闭窗口
			closeDialog() {
				this.showCropper = false;

				if (!this.noCanUpload) {
					let fileList = this.$refs.fileUpload.uploadFiles // 获取文件列表
					let index = fileList.findIndex(item => { // 把取消裁剪的图片删除
						return item.uid == this.currentFile.uid;
					});
					fileList.splice(index, 1)
				}
			},
			// 上传图片
			uploadImg(file) {
				this.uploadFile = file;
				this.$refs.fileUpload.submit();
                
				// 判断裁剪后图片的宽高
				// let img = new Image()
				// img.src = window.URL.createObjectURL(file); // Blob转成url 才能给img显示
				// img.onload = () => {
				// 	let minProp = Math.min(img.width, img.height) //裁剪后的图片宽，高 ==> 取最小值
				// 	if (minProp < 200) { // 如果最小值比设置的最小值（默认为200）小
				// 		this.$message.error(`请保证图片短边最小为200`);
				// 		return false
				// 	}
				// 	this.$refs.fileUpload.submit();
				// }
			},
			selectChange(file) {
				console.log(file)
				this.noCanUpload = false
				let files = file.raw;
				
				var reader = new FileReader();
				reader.onload = e => {
					let data;
					if (typeof e.target.result === "object") {
						// 把Array Buffer转化为blob 如果是base64不需要
						data = window.URL.createObjectURL(new Blob([e.target.result]));
					} else {
						data = e.target.result;
					}
					this.cropperImg = data;

					if(this.isCropper){//是否开启裁剪
						// 图片图片尺寸，如果是正方形，则直接上传；否则调用裁剪
						let img = new Image()
						img.src = this.cropperImg;
						img.onload = () => {
							// if (img.width == img.height) { // 本来就是正方形 => 直接上传
							// 	this.uploadFile = files;
							// 	this.$refs.fileUpload.submit(); // 调用上传方法
							// } else {
							// 	this.showCropper = true; // 不是正方形的图片才开启裁剪
							// 	this.currentFile = file // 保存当前操作裁剪的图片
							// }
							this.showCropper = true;
							this.currentFile = file
						}
					}else{
						this.uploadFile = files;
						this.$refs.fileUpload.submit(); // 调用上传方法
					}
				};
				// 转化为base64
				// reader.readAsDataURL(file)
				// 转化为blob
				reader.readAsArrayBuffer(files);

				// this.showCropper = true;  // 默认开启裁剪
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			}
		}
	};
</script>

<style lang="scss">
	
</style>
